<!--输入框组件
inputType: number:只支持数字和小数点
dataType： int:整数形式

-->
<template>
  <div>
    <!-- eslint-disable-next-line -->
    <el-input ref="inputDom" :size="config.size" v-model="form.data.input" :disabled="config.disabled" :class="config.childClass" :maxlength="config.maxlength" :placeholder="config.placeholder" :show-word-limit="config.showWordLimit" :clearable="config.clearable || true" :type="inputType" :style="config.childStyle || {width:'100%;'}" @blur="eventFn('blur')">
      <!-- 前缀图标 -->
      <i v-if="prefixIcon" slot="prefix" :class="prefixIcon" class="prefixIcon-cls el-input__icon iconfont" ></i>
      <!-- 后缀图标 -->
      <i v-if="suffixIcon" slot="suffix" :class="suffixIcon" class="el-input__icon iconfont" @click="suffixHandler" ></i>
      <slot slot="append" name="inputPart" ></slot>
    </el-input>
    <span v-show="config.splitText" class="split-cls">-</span>
    <slot name="other" ></slot>
  </div>
</template>

<script>
export default {
  name: 'FormInput',
  props: {
    // 是否可编辑
    // disabled: {
    //   type: Boolean,
    //   required: false,
    //   default: false
    // },
    // 组件循环时需要的idx值
    idx: {
      type: [Number, String],
      default: 0
    },
    // 参数配置
    config: {
      type: Object,
      required: false,
      default: () => {
        return {
          label: '文本输入',
          name: 'text',
          placeholder: '请填写文本输入',
          clearable: true,
          disabled: false,
          rules: [
            { required: true, message: '请输入文本输入', trigger: 'blur' }
          ]
        }
      }
    },
    data: {
      type: [String, Number],
      required: false,
      default: ''
    }
  },
  data () {
    return {
      inputType: 'text',
      form: {
        data: {
          input: ''
        }
      }
    }
  },
  computed: {
    // 前缀icon
    prefixIcon () {
      let cls = this.config.prefixIcon
      if (cls) {
        cls = cls.split(',')
      }
      return cls
    },
    // 后缀icon
    suffixIcon () {
      let cls = this.config.suffixIcon
      if (cls) {
        cls = cls.split(',')
      }
      return cls
    },
    formItemClass () {
      let clsStr = this.$common.deepCloneObj(this.config.formItemClass)
      if (this.config.prefixIcon) {
        // debugger
        if (clsStr) {
          const type = this.$common.getType(clsStr)
          // debugger
          if (type === 'array') {
            clsStr.push('has-prefix-icon')
          } else if (type === 'object') {
            clsStr['has-prefix-icon'] = true
          }
        } else {
          clsStr = ['has-prefix-icon']
          // debugger
        }
      }

      if (this.config.splitText) {
        const type = this.$common.getType(clsStr)
        if (type === 'array') {
          clsStr.concat(['mg-l0', 'mg-r0'])
        } else if (type === 'object') {
          clsStr['mg-l0'] = true
          clsStr['mg-r0'] = true
        } else {
          clsStr += ' ' + 'mg-l0 mg-r0'
        }
      }
      // debugger
      return clsStr
    }
  },
  watch: {
    config: {
      handler (obj) {
        // debugger
        this.inputType = obj.type
      },
      deep: true,
      immediate: true
    },
    data: {
      handler (val) {
        // debugger
        this.form.data.input = val
      },
      deep: true,
      immediate: true
    },
    // 监听到form的数据变化则把config.name和form.data.input和idx传到父组件
    form: {
      handler (val) {
        // debugger
        if (this.config.inputType === 'number') {
          let num = '' + this.form.data.input
          const isPointLast = num.indexOf('.') === num.length - 1
          // debugger
          if (!isPointLast) {
            num = num.replace(/[^\-?\d.]/g, '') // 去除非数字字符，不包含小数点
            // 整形
            if (this.config.dataType === 'int') {
              this.form.data.input = this.limitNum(parseInt(num))
            } else {
              this.form.data.input = this.limitNum(num)
            }
          }
        }
        this.$emit('updateForm', '' + this.config.name, this.form.data.input, this.idx, this.config)
      },
      deep: true
    }
  },
  mounted () {
    if (
      this.config.inputType === 'number' &&
      this.config.dataType !== 'int' &&
      this.config.rules
    ) {
      // debugger
      this.config.rules.push({
        validator: (rule, value, callback) => {
          // debugger
          this.validateSku(rule, value, callback)
        },
        trigger: ['blur', 'change']
      })
    }
  },
  methods: {
    // 事件回调
    eventFn (eventName) {
      this.$emit('eventCB', { eventName, value: this.form.data.input, idx: this.idx, config: this.config })
    },
    // 获取焦点 触发
    focus () {
      this.$refs.inputDom.focus()
    },
    // 失去焦点 触发
    blur () {
      this.$refs.inputDom.blur()
    },
    /**
     * 后缀图标点击事件
     */
    suffixHandler () {
      // debugger
      if (this.config.type === 'password') {
        // 密码图标切换事件
        if (this.inputType !== this.config.type) {
          this.inputType = this.config.type
        } else {
          this.inputType = 'text'
        }
      }
    },
    /**
     * 校验数字输入（允许小数点）
     * @method 自定义校验方法
     * callback 必须调用
     */
    validateSku (rule, value, callback) {
      const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g
      var matchStr = value.match(reg)
      // console.log('matchStr', matchStr)
      if (!matchStr) {
        callback(new Error('输入无效'))
      } else {
        callback()
      }
    },
    /**
     * 最大最小值
     */
    limitNum (val) {
      // debugger
      if (!this.$validate.isNull(this.config.min)) {
        val = Math.max(val, this.config.min)
      }

      if (!this.$validate.isNull(this.config.max)) {
        val = Math.min(val, this.config.max)
      }
      return '' + val
    }
  }
}
</script>

<style lang="scss" scoped>
.split-cls {
  margin-right: 5px;
}
// /deep/ .el-form-item .el-input__prefix {
//   left: 7px;
//   top: 2px;
//   width: 22px;
// }
</style>

